package com.lky.marshallmall.product.web;

import com.lky.marshallmall.product.config.MyRedissonConfig;
import com.lky.marshallmall.product.entity.CategoryEntity;
import com.lky.marshallmall.product.service.CategoryService;
import com.lky.marshallmall.product.vo.Catelog2Vo;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created by
 * autor : Marshall lky
 * datetime: 2021/3/29 10:54
 */
@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedissonClient redisson;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        //1.查出所有1级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categoies();

        model.addAttribute("categories", categoryEntities);
        return "index";
    }

    @GetMapping("/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catelog2Vo>> getCateLogJson() {
        Map<String, List<Catelog2Vo>> map = categoryService.getCateLogJson();
        return map;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() throws Exception {
        //获取一把锁，只要锁的名字一样，就是同一把锁
        RLock lock = redisson.getLock("my-lock");
        //加锁
        lock.lock();//阻塞式等待
//        lock.lock(10, TimeUnit.SECONDS);//10秒后自动解锁,自动解锁时间要大于业务执行时间
        /*
        如果传递了锁的超时时间，就发送给redis脚本，执行占锁，默认超时时间就是设置的超时时间。
        如果未传递，就使用30*1000【LockWatchTimeOut看门狗的默认时间】;
        只要占锁成功，就会启动一个定时任务【重新给锁设置过期时间（看门狗默认时间）】
        */
        //redisson解决了锁的自动续期，如果业务超长，运行期间自动给锁续30秒，锁自动过期被删掉
        //加锁的业务只要运行完成，不会给当前锁续期，即使不手动解锁，默认30秒自动删除
        try {
            System.out.println("加锁成功。。。业务代码" + Thread.currentThread().getId());
            Thread.sleep(30000);
        } finally {
            //解锁
            System.out.println("释放锁" + Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }


    @GetMapping("/write")
    @ResponseBody
    public String writeValue() {
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.writeLock();
        try {
            //改数据加写锁
            rLock.lock();
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            stringRedisTemplate.opsForValue().set("writeValue", s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }

        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public String readValue() {
        String s = "";
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.readLock();
        //读数据用读锁
        rLock.lock();
        try {
            s = stringRedisTemplate.opsForValue().get("writeValue");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }
        return s;
    }


    /**
     * 5个计数线程 每个线程到0才能返回结果
     */
    @GetMapping("/lockDoor")
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();//等待闭锁完成

        return "success";
    }

    @GetMapping("/countGO/{id}")
    public String countGO(@PathVariable("id") Long id) {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown(); //计数减1
        return id + "线程执行完";
    }


    public static void main(String[] args) throws ParseException {
        int[] arr = {1,2,3,2,3,1};
        //用链表实现队列，队列是先进先出的
        Queue<Integer> queue = new LinkedList<>();
        int res = 0;
        for (int c : arr) {
            while (queue.contains(c)) {
                //如果有重复的，队头出队
                queue.poll();
            }
            //添加到队尾
            queue.add(c);
            res = Math.max(res, queue.size());
        }
        System.out.println(res);

    }

}
